﻿using Newtonsoft.Json;
using NoteBook_Shared.Contact;
using RestSharp;

namespace NoteBook_Product.Services
{
    /// <summary>
    /// http请求通用类
    /// </summary>
    public class HttpRestClient
    {
        private readonly string _apiUrl;
        protected readonly RestClient _client;

        public HttpRestClient(string apiUrl)
        {
            _apiUrl = apiUrl;
            _client = new RestClient();
        }

        public async Task<ApiResponse> ExecuteAsync(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);

            if (baseRequest.Parameter != null)
            {
                request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            }
            _client.BaseUrl = new Uri(_apiUrl + baseRequest.Rotue);
            var response = await _client.ExecuteAsync(request);

            return JsonConvert.DeserializeObject<ApiResponse>(response.Content)!;
        }

        public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);

            if (baseRequest.Parameter != null)
            {
                request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            }
            _client.BaseUrl = new Uri(_apiUrl + baseRequest.Rotue);
            var response = await _client.ExecuteAsync(request);

            return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content)!;
        }
    }
}
